#include "ReadNavFile.h"

ReadNavFile::ReadNavFile(const std::string& path) : filePath(path) {
    parseNavFile();
}

void ReadNavFile::parseNavFile() {
    std::ifstream file(filePath);
    if (!file.is_open()) {
        std::cerr << "Failed to open Rinex navigation file: " << filePath << std::endl;
        return;
    }

    std::string line;
    while (std::getline(file, line)) {
        if (line.find("END OF HEADER") != std::string::npos) {
            continue;
        }

        if (line.length() >= 4 && line[0] == 'C') {
            SatelliteEphemeris eph;
            eph.satelliteId = line.substr(0, 3);

            std::vector<double> params;
            for (int i = 4; i < line.length(); i += 12) {
                if (i + 12 > line.length()) break;
                std::string paramStr = line.substr(i, 12);
                try {
                    params.push_back(std::stod(paramStr));
                }
                catch (const std::invalid_argument& e) {
                    std::cerr << "Invalid argument when converting string to double: " << paramStr << std::endl;
                }
                catch (const std::out_of_range& e) {
                    std::cerr << "Out of range when converting string to double: " << paramStr << std::endl;
                }
            }
            eph.ephemerisParams = params;

            ephemerisData.push_back(eph);
        }
    }

    file.close();
}

std::vector<double> ReadNavFile::getEphemerisParams(const std::string& satelliteId) {
    for (const auto& eph : ephemerisData) {
        if (eph.satelliteId == satelliteId) {
            return eph.ephemerisParams;
        }
    }

    std::cerr << "Ephemeris data not found for satellite: " << satelliteId << std::endl;
    return {};
}